Central Article

Understanding and Using the LCService Library

Ethan Malasky

Ethan Malasky
Macromedia

Good application design in Macromedia Central stipulates using an agent that coordinates network access, application logic, and data management for applications and their pods. Although applications, pods, and agents can communicate with each other using LocalConnection, this quickly becomes messy—leaving you to wrangle with the challenges of writing an agent that can handle individual client requests and broadcast events to all clients. To solve these common problems, Macromedia provides the LCService library. Because it is built directly into the Central player, your applications won't become bloated with LCService code.

This article introduces you to the LCService library. It explains the problems it solves and demonstrates with code how to leverage its functionality. It also describe common application patterns that should be eased by libraries like LCService, or by extensions to LCService itself. It also describes the LCService security mechanism.

Note: LCService supports a client-server model. Your agent SWF plays the role of the server and handles requests from the clients, application instances, and pods. Please note that "server" in this context does not refer to a remote machine.

What LCService Does

The LCService library makes it easy to develop a client-server communication channel between your applications and pods (clients) and your agent (server). Clients and servers have different roles due to the one-to-many relationship: Each client talks to one server only, but one server can handle multiple clients.

LCService is based on LocalConnection objects (hence the "LC" prefix) and provides a layer of syntactic sugar that simplifies remote method invocation and handling of return values. Instead of using LocalConnection directly and calling the following:

lc.send("_somecomplicatedaddress", "methodname", args )

You simply say what you mean:

service.methodname( args );

LocalConnection objects are limited in that they're one-way connections; you have to manage your own return values. LCService helpfully does this for you, too, using the same pattern as Flash Remoting. So you can write the following:

service.methodname_Result = function( result )
{
   trace("methodname returned: "+result);
}

service.methodname( args );

If both the client and receiver reside inside Central, they can take advantage of a Central-only feature: synchronous LocalConnection. This lets you code even more naturally:

var result = service.methodname( args );
trace("methodname returned: "+result);

At this point, you might even forget that you're communicating with another Flash movie in an entirely different window!

How to Use LCService

LCService borrows a page from C++, Java, and other programming languages by using interfaces to determine which methods can be called.

Note: ActionScript 2.0 also has Java-style interfaces. Because LCService is compatible with ActionScript 1.0, LCService uses an object-based implementation of Interfaces.

An interface is an object with special fields. Let's look at an example. Suppose your test service is an alarm clock. Clients can call the single server to set an alarm time or check what time is set. The server, in turn, can call the clients when the alarm rings:

var ITestService = {};
ITestService.name = "com.macromedia.samples.ITestService";
ITestService.interfaces = {};
ITestService.interfaces["Server"] = [ "setAlarm", "getAlarm" ];
ITestService.interfaces["Client"] = [ "onAlarmRing" ];

Here's what the various properties mean:

  • The name property should be globally unique; it identifies the communication endpoint for your server and clients
  • The interfaces.Server property is an array of strings, listing the methods callable on the server by the clients
  • The interfaces.Client property is an array of strings, listing the methods callable on the clients by the server

A reference to this Interface object is passed in to the constructors for both client and server LCService objects.

Another object used with LCService is the callback object. The clients and server have different callback objects, which implement the methods defined in the interface for that side (client or server) of the LCService. This object can also be a movie clip, which is what I use in these examples.

The following code defines the server:

// defines callback functions
function setAlarm( time )
{
   this.fAlarmTime = time;

   // set an interval appropriately
   [ . . .]
}

function getAlarm()
{
   return this.fAlarm;
}

function onActivate( agentManager, agentId, initialData )
{
   this.fAgentManager = agentManager;

   // create LCService Server
   this.fService = Central.LCService.createServer( ITestService, this );
}

Looking at the createServer() call, you can see two parameters passed in. The first one is the Interface object defined above. The second is the callback object, which in this case is the same as the movie clip running onActivate().

There is a similar LCService factory method to create clients as well. Clients need to specify a unique ID so that the server can tell them apart. In Central, a unique ID can be created by combining the appId and the shellId (in an application), or the podId and the viewerId (in a pod).

The following code defines the client:

function onAlarmRing()
{
   // make the screen flash
   this.gotoAndPlay( "flash" );
}

function onActivate( shell, appId, shellId, bastTabIndex, initialData )
{
   this.fShell = shell;
   this.fAppId = appId;
   this.fShellId = shellId;

   // Generate client id
   this.fClientId = String(this.fAppId+"_"+this.fShellId);

   // Create LCService Client
   this.fService = Central.LCService.createClient( ITestService, this.fClientId, this );
}

Note that the clients and server need to agree on the definition of ITestService. In practice, it helps to keep the interface definition in a shared source file that you include in all your FLAs, as follows:

#include "Interfaces.as"

Figure 1 shows the relationship between the client and server LCService objects and callback objects used in this example.

Relationship between client and server LCService objects and callback objects

Figure 1. Relationship between client and server LCService objects and callback objects

Synchronous versus Asynchronous Return Values

LCService supports two modes of operation, which determine when the function being called actually gets called, and affect the caller's method of getting return values from that function.

Synchronous Mode

When LCService runs synchronously, a function invoked over LCService gets called immediately, and its value is returned as from a normal function call. This lets you say the following:

var alarmTime = service.getAlarm();
trace("Alarm at: "+ alarmTime);

To use LCService synchronously, both sides of the LCService must be running in Central. An extra parameter is passed to the LCService.createClient() and LCService.createServer() functions:

// SERVER
   this.fService = Central.LCService.createServer( ITestService, this, true );

   // CLIENT
   this.fService = Central.LCService.createClient( ITestService, this.fClientId, this, true );

Asynchronous Mode

When LCService runs asynchronously, there will be a delay between when one side calls the function and when the other side receives the call. This delay allows time for the Central player to perform other operations (updating the display, and so on). Return values are also delayed and are returned through a callback function, which has the same name as the method but appended with _Result:

function getAlarm_Result( result )
{
   trace("Alarm at: " + result );
}

   service.getAlarm();

Who Calls Whom?

LCService has built-in support for a one-to-many relationship between a server and its clients. This means that when client code invokes a method on its LCService object, the method is called on the single server.

However, when server code invokes a method on its LCService object, that call behaves as a broadcast: The method is invoked on every client. This means that your server code (running in the agent) can call one function and all of your clients (applications, pods) will get the message.

The downside to this broadcast convenience is handling return values. LCService does not support return values from broadcast calls.

Cleaning Up Endpoints

Each side of an LCService has its own unique communication endpoint (using LocalConnection). These endpoints must be cleaned up when they are no longer needed, so that they will be available the next time they are needed. Failing to call close() prevents your LCService clients from making remote calls after the user switches to another application and then back to yours. The way to do this is to call close() on LCService objects. The onDeactivate() function, which is called by Central when your application, pod, or agent is about to be unloaded, is a natural place for this:

function onActivate( shell, appId, shellId, bastTabIndex, initialData )
{
   this.fShell = shell;
   this.fAppId = appId;
   this.fShellId = shellId;

   // Generate client id
   this.fClientId = String(this.fAppId+"_"+this.fShellId);

// Create LCService Client
   this.fService = Central.LCService.createClient( ITestService, this.fClientId, this );
}

function onDeactivate()
{
   // CLEAN up my endpoint
   this.fService.close();
}

Solving the Startup Race

I'm getting into expert territory now, so hang on. When you start Macromedia Central, it loads several SWF files, including (perhaps) your application, your agent, and one or more instances of your pod(s). The biggest problem this raises is that when an application or pod starts, it cannot necessarily call its agent right away because the agent may not have finished loading; even if its SWF is loaded, it may need to perform its own initialization before it's ready to serve requests.

To deal with this race condition upon startup, LCService calls a special function on your client callback objects to indicate whether it has contacted your LCService server. The createClient_Result() function indicates a success case; createClient_Status() indicates a failure:

function onActivate( shell, appId, shellId, bastTabIndex, initialData )
{
   this.fShell = shell;
   this.fAppId = appId;
   this.fShellId = shellId;

   // Generate client id
   this.fClientId = String(this.fAppId+"_"+this.fShellId);

// Create LCService Client
   this.fService = Central.LCService.createClient( ITestService, this.fClientId, this );
}

function createClient_Result( clientObj )
{
   // Now we know that we can call methods on the service!
   this.fService.getAlarm();
}

function createClient_Status( clientObj )
{
   // Something went ill; the Agent didn't get started in time.
   raiseSomeMessageToUser();
}

Both functions pass a single parameter, a reference to the LCService client object being created. This parameter is useful if your callback object is being used as the callback object for multiple LCService clients; otherwise, it can safely be ignored.

Behind the scenes, the LCService client solves the startup race condition for you. It uses a simple technique: It calls the server to register and if the call doesn't go through (as indicated by a return value) it waits a second before trying again. There is a limit to this: After 10 seconds, the LCService client gives up, assumes the server will never be available, and calls your createClient_Status() handler.

Security and LCService

LCService inherits its security mechanism from LocalConnection.allowDomain(). The LCService client and server can each define an allowDomain() function that specifies which domains are allowed to make a call. Additionally, the LCService client and server inherit LocalConnection.domain(), which provides an easy way to know your own domain, without hard-coding. For example:

// SERVER 
this.fService = Central.LCService.createServer(ITestService, this, true ); 
this.fService.allowDomain = function( callerDomain )
{
   // allow callers from my domain (note that "this" refers to fService)
   if( callerDomain == this.domain() )
   {
      return true;
   }
   // allowCallers from "vortech.org"
   if( callerDomain == "vortech.org" )
   {
      return true;
   }
   // everyone else loses
   return false;
};

This flexible technique allows developers to create agents that offer services to applications from any domain, or from a desired subset of domains. When no allowDomain() function is defined, the default behavior allows callers only from the same domain.

Note: When calling a service in another domain, it is not enough for the server to permit calls from the client's domain. In order for LCService to function properly, the client must also use allowDomain() to allow calls from the server's domain.

LCService Resources

Hopefully you now have a sense of how the LCService library makes it easier for you to build robust, flexible applications for Central. Let's review the steps for developing with LCService:

  1. Define your Interface object, which lists the methods implemented by the client, and which by the server.
  2. Create a callback object containing functions that implement the client or server's methods—and, on the client side, result functions for the server's methods.
  3. Use the factory functions Central.LCService.createClient() and Central.LCService.createServer() to instantiate LCService objects.
  4. Call methods on the LCService objects to invoke remote methods.

The developer libraries for Central, including LCService, are living products. As we learn more about the problems developers try to solve, we can create better and better tools to help. Already now there is a growing number of ideas about how to improve LCService. As these ideas come to you, please feel free to share them with me and the rest of the Central developer community.

Here are some more resources to check out:


About the author

Ethan Malasky is a developer on the Macromedia Central team. He was instrumental in designing the Central architecture as well as the preferred architecture for Central applications. His responsibilities include defining and implementing technologies to support the growing Central developer community. He also fixes bugs.